{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://github.com/optuna/optuna-examples/blob/main/visualization/plot_study.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualizing High-dimensional Parameter Relationships\n",
    "\n",
    "This notebook demonstrates various visualizations of studies in Optuna.\n",
    "The hyperparameters of a neural network trained to classify images are optimized and the resulting study is then visualized using these features.\n",
    "\n",
    "**Note:** If a parameter contains missing values, a trial with missing values is not plotted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If you run this notebook on Google Colaboratory, uncomment the below to install Optuna.\n",
    "#! pip install --quiet optuna"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparing the Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import fetch_openml\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "mnist = fetch_openml(name=\"Fashion-MNIST\", version=1)\n",
    "classes = list(set(mnist.target))\n",
    "\n",
    "# For demonstrational purpose, only use a subset of the dataset.\n",
    "n_samples = 4000\n",
    "data = mnist.data[:n_samples]\n",
    "target = mnist.target[:n_samples]\n",
    "\n",
    "x_train, x_valid, y_train, y_valid = train_test_split(data, target)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Defining the Objective Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neural_network import MLPClassifier\n",
    "\n",
    "\n",
    "def objective(trial):\n",
    "\n",
    "    clf = MLPClassifier(\n",
    "        hidden_layer_sizes=tuple(\n",
    "            [trial.suggest_int(\"n_units_l{}\".format(i), 32, 64) for i in range(3)]\n",
    "        ),\n",
    "        learning_rate_init=trial.suggest_float(\"lr_init\", 1e-5, 1e-1, log=True),\n",
    "    )\n",
    "\n",
    "    for step in range(100):\n",
    "        clf.partial_fit(x_train, y_train, classes=classes)\n",
    "        value = clf.score(x_valid, y_valid)\n",
    "\n",
    "        # Report intermediate objective value.\n",
    "        trial.report(value, step)\n",
    "\n",
    "        # Handle pruning based on the intermediate value.\n",
    "        if trial.should_prune():\n",
    "            raise optuna.TrialPruned()\n",
    "\n",
    "    return value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Running the Optimization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import optuna\n",
    "\n",
    "optuna.logging.set_verbosity(\n",
    "    optuna.logging.WARNING\n",
    ")  # This verbosity change is just to simplify the notebook output.\n",
    "\n",
    "study = optuna.create_study(direction=\"maximize\", pruner=optuna.pruners.MedianPruner())\n",
    "study.optimize(objective, n_trials=100)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing the Optimization History"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optuna.visualization import plot_optimization_history\n",
    "\n",
    "plot_optimization_history(study)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing the Learning Curves of the Trials"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optuna.visualization import plot_intermediate_values\n",
    "\n",
    "plot_intermediate_values(study)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing High-dimensional Parameter Relationships"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optuna.visualization import plot_parallel_coordinate\n",
    "\n",
    "plot_parallel_coordinate(study)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Selecting Parameters to Visualize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_parallel_coordinate(study, params=[\"lr_init\", \"n_units_l0\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing Parameter Relationships"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optuna.visualization import plot_contour\n",
    "\n",
    "plot_contour(study)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Selecting Parameters to Visualize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_contour(study, params=[\"n_units_l0\", \"n_units_l1\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing Individual Parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optuna.visualization import plot_slice\n",
    "\n",
    "plot_slice(study)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Selecting Parameters to Visualize"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_slice(study, params=[\"n_units_l0\", \"n_units_l1\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing Parameter Importances"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from optuna.visualization import plot_param_importances\n",
    "\n",
    "plot_param_importances(study)"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "include_colab_link": true,
   "name": "plot_study.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
